package io.dy.handler;

import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.LongAdder;

/**
 * @author : dmj
 * @date: 2024/7/22 5:49 下午
 * @description:
 */
public class MergeHandler implements RowWriteHandler {

    private final LongAdder count = new LongAdder();

    @Override
    public void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer integer, Boolean aBoolean) {
        count.increment();
        System.out.println("=============> 进入次数：" + count.intValue());
        Sheet sheet = writeSheetHolder.getSheet();
        List<CellRangeAddress> rangeAddressList = new ArrayList<>();
        List<CellRangeAddress> mergedRegions = sheet.getMergedRegions();
        mergedRegions.forEach(m -> {
            if (m.getFirstRow() == row.getRowNum() - 1 && m.getLastRow() == row.getRowNum() - 1) {
                    rangeAddressList.add(new CellRangeAddress(row.getRowNum(), row.getRowNum(), m.getFirstColumn(), m.getLastColumn()));
            }
        });
        if (!CollectionUtils.isEmpty(rangeAddressList)) {
            // 设置单元格边框
            CellStyle cellStyle = sheet.getWorkbook().createCellStyle();
            cellStyle.setBorderRight(BorderStyle.THIN);
            cellStyle.setBorderLeft(BorderStyle.THIN);
            cellStyle.setBorderTop(BorderStyle.THIN);
            cellStyle.setBorderBottom(BorderStyle.THIN);
            for (int i = 1; i < 12; i++) {
                Cell cell = row.createCell(i);
                cell.setCellStyle(cellStyle);
            }
            rangeAddressList.forEach(sheet::addMergedRegion);
        }
    }
}
